package com.fc.test.service;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.fc.test.mapper.auto.*;
import com.fc.test.model.auto.*;
import com.fc.test.util.DateUtil;
import com.fc.test.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.fc.test.common.base.BaseService;
import com.fc.test.common.support.Convert;
import com.fc.test.model.custom.Tablepar;
import com.fc.test.util.SnowflakeIdWorker;
import org.springframework.transaction.annotation.Transactional;

/**
 * 提现申请记录表Service
* @Title: TAbbWithdrawService.java 
* @Package com.fc.test.entity 
* @author fuce
* @email 87766867@qq.com
* @date 2019-08-26 18:38:32  
 */
@Service
public class TAbbWithdrawService implements BaseService<TAbbWithdraw, TAbbWithdrawExample>{
	@Autowired
	private TAbbWithdrawMapper tAbbWithdrawMapper;

	@Autowired
	private TAbbMemberMapper memberMapper;

	@Autowired
	private TAbbTixianMapper tixianMapper;
	@Autowired
	private TAbbCountMapper tAbbCountMapper;
	@Autowired
	private TAbbCommissionMapper tAbbCommissionMapper;

	@Autowired
	private TAbbMemberMapper tAbbMemberMapper;

	/**
	 * 分页查询
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	 public PageInfo<TAbbWithdraw> list(Tablepar tablepar,String name,String status,String starttime,String endtime){
	        TAbbWithdrawExample testExample=new TAbbWithdrawExample();
	        testExample.setOrderByClause("id ASC");
		 TAbbWithdrawExample.Criteria criteria=testExample.createCriteria();
	        if(name!=null&&!"".equals(name)){
				criteria.andUsernameLike("%"+name+"%");
	        }
			 if(status!=null&&!"".equals(status)&&!status.equals("-1")){
				 criteria.andStatusEqualTo(Integer.parseInt(status));
			 }
			 if(!StringUtils.isBlank(starttime)){
				 criteria.andCreattimeGreaterThanOrEqualTo(starttime);
			 }
			 if(!StringUtils.isBlank(endtime)){
				 criteria.andCreattimeLessThanOrEqualTo(endtime);
			 }
	        PageHelper.startPage(tablepar.getPageNum(), tablepar.getPageSize());
	        List<TAbbWithdraw> list= tAbbWithdrawMapper.selectByExample(testExample);
	        PageInfo<TAbbWithdraw> pageInfo = new PageInfo<TAbbWithdraw>(list);
	        return  pageInfo;
	 }

	@Override
	public int deleteByPrimaryKey(String ids) {
		List<String> lista=Convert.toListStrArray(ids);
		TAbbWithdrawExample example=new TAbbWithdrawExample();
		example.createCriteria().andIdIn(lista);
		return tAbbWithdrawMapper.deleteByExample(example);
	}


	@Override
	public TAbbWithdraw selectByPrimaryKey(String id) {

		return tAbbWithdrawMapper.selectByPrimaryKey(id);
	}


	@Override
	public int updateByPrimaryKeySelective(TAbbWithdraw record) {
		return tAbbWithdrawMapper.updateByPrimaryKeySelective(record);
	}

	/**
	 * 添加
	 */
	@Override
	public int insertSelective(TAbbWithdraw record) {
		//添加雪花主键id
		record.setId(SnowflakeIdWorker.getUUID());
		return tAbbWithdrawMapper.insertSelective(record);
	}










	@Override
	public int updateByExampleSelective(TAbbWithdraw record, TAbbWithdrawExample example) {

		return tAbbWithdrawMapper.updateByExampleSelective(record, example);
	}


	@Override
	public int updateByExample(TAbbWithdraw record, TAbbWithdrawExample example) {

		return tAbbWithdrawMapper.updateByExample(record, example);
	}

	@Override
	public List<TAbbWithdraw> selectByExample(TAbbWithdrawExample example) {

		return tAbbWithdrawMapper.selectByExample(example);
	}


	@Override
	public long countByExample(TAbbWithdrawExample example) {

		return tAbbWithdrawMapper.countByExample(example);
	}


	@Override
	public int deleteByExample(TAbbWithdrawExample example) {

		return tAbbWithdrawMapper.deleteByExample(example);
	}


	@Transactional
	public Map<String,Object> applyWithdraw(String userid,double totalmoney,String alipayAccount){
		Map<String,Object> resMap = new HashMap<>();
		TAbbMember member = memberMapper.selectByPrimaryKey(userid);
		double account = member.getAccount();
		if(account<totalmoney){
			resMap.put("success",false);
			resMap.put("msg","提现金额需小于钱包余额");
			return resMap;
		}

		TAbbTixianExample testExample=new TAbbTixianExample();
		testExample.setOrderByClause("id ASC");
		PageHelper.startPage(1, 1);
		List<TAbbTixian> list= tixianMapper.selectByExample(testExample);
		TAbbTixian tixian = list.get(0);

		//添加提现申请记录
		TAbbWithdraw withdraw = new TAbbWithdraw();
		double fee = 0d;
		double sfee = 0d;
		double realmoney = 0d;
		DecimalFormat df = new DecimalFormat("#.00");

		long vipendtime = 0l;
		long now = new Date().getTime();
		if(null!=member.getVipendtime()&&!"".equals(member.getVipendtime())){
			vipendtime = member.getVipendtime().getTime();
		}
		String yqrId = member.getYqrid();
		TAbbMember yqr = memberMapper.selectByPrimaryKey(yqrId);
		if(member.getIsshop()==1 && "0".equals(member.getYuliu3())){
			fee = 0d;
			sfee = 0d;
			realmoney = totalmoney;
			withdraw.setYuliu2("2");
		}else{
			if(member.getIsvip()==1&&now<vipendtime){
				if(null!=yqrId&&!"".equals(yqrId)&&yqr.getIsvip()==1){
					fee = totalmoney*(Double.parseDouble(tixian.getVip())/100);
					sfee = totalmoney*(Double.parseDouble(tixian.getSvip())/100);
				}else{
					fee = totalmoney*((Double.parseDouble(tixian.getVip())+Double.parseDouble(tixian.getSvip()))/100);
					sfee = 0d;
				}
				realmoney = totalmoney-fee-sfee;
				withdraw.setYuliu2("3");
			}else{
				if(null!=yqrId&&!"".equals(yqrId)&&yqr.getIsvip()==1){
					fee = totalmoney*(Double.parseDouble(tixian.getMember())/100);
					sfee = totalmoney*(Double.parseDouble(tixian.getSmember())/100);
				}else{
					fee = totalmoney*((Double.parseDouble(tixian.getMember())+Double.parseDouble(tixian.getSmember()))/100);
					sfee = 0d;
				}
				realmoney = totalmoney-fee-sfee;
				withdraw.setYuliu2("1");
			}
		}

		withdraw.setId(SnowflakeIdWorker.getUUID());
		withdraw.setCreattime(DateUtil.getCurrentDateTimeStr());
		withdraw.setUserid(userid);
		withdraw.setUsername(member.getNicename());
		withdraw.setTotalmoney(totalmoney);
		withdraw.setFee(Double.valueOf(df.format(fee)));
		withdraw.setSfee(Double.valueOf(df.format(sfee)));
		withdraw.setRealmoney(Double.valueOf(df.format(realmoney)));
		withdraw.setStatus(1);
		withdraw.setYuliu1(alipayAccount);
		int flag = tAbbWithdrawMapper.insert(withdraw);

		if(flag>0){
			//从用户账户减去提现金额
			member.setAccount(Double.valueOf(df.format(account-totalmoney)));
			memberMapper.updateByPrimaryKey(member);
			resMap.put("success",true);
			resMap.put("msg","提交成功，请耐心等待审核");
			resMap.put("account",df.format(account-totalmoney));
		}else{
			resMap.put("success",false);
			resMap.put("msg","提交失败");
		}
		return resMap;
	}


	public Map<String,Object> getTixianbili(String userid){
		Map<String,Object> resMap = new HashMap<>();
		TAbbMember member = memberMapper.selectByPrimaryKey(userid);
		TAbbTixianExample testExample=new TAbbTixianExample();
		testExample.setOrderByClause("id ASC");
		PageHelper.startPage(1, 1);
		List<TAbbTixian> list= tixianMapper.selectByExample(testExample);
		TAbbTixian tixian = list.get(0);
		//计算手续费
		if(member.getIsshop()==1 && "0".equals(member.getYuliu3())){
			resMap.put("isVip","2");
			resMap.put("msg","是商家，不用收取手续费");
		}else{
			long vipendtime = 0l;
			long now = new Date().getTime();
			if(null!=member.getVipendtime()&&!"".equals(member.getVipendtime())){
				vipendtime = member.getVipendtime().getTime();
			}
			DecimalFormat df = new DecimalFormat("#.00");
			if(member.getIsvip()==1&&now<vipendtime){
				resMap.put("isVip","1");
				resMap.put("tixian",tixian.getVip());
				resMap.put("stixian",tixian.getSvip());
				double fee = Double.parseDouble(tixian.getVip())+Double.parseDouble(tixian.getSvip());
				resMap.put("msg","VIP用户提现平台扣除服务费"+df.format(fee)+"%");
			}else{
				resMap.put("isVip","0");
				resMap.put("tixian",tixian.getMember());
				resMap.put("stixian",tixian.getSmember());
				double vipFee = Double.parseDouble(tixian.getVip())+Double.parseDouble(tixian.getSvip());
				double fee = Double.parseDouble(tixian.getMember())+Double.parseDouble(tixian.getSmember());
				resMap.put("msg","VIP用户提现平台扣除服务费"+df.format(vipFee)+"%,普通用户提现扣除"+df.format(fee)+"%!");
			}
		}

		resMap.put("success",true);
		return resMap;
	}

	@Transactional
    public int tixianshenhe(TAbbWithdraw record) {
		TAbbWithdraw tAbbWithdraw=tAbbWithdrawMapper.selectByPrimaryKey(record.getId());
		TAbbMember tAbbMember1=memberMapper.selectByPrimaryKey(tAbbWithdraw.getUserid());

		//提现失败返还用户钱
		if (record.getStatus()==3){
			TAbbMember tAbbMember=new TAbbMember();
			tAbbMember.setAccount(tAbbMember1.getAccount()+tAbbWithdraw.getTotalmoney());
			tAbbMember.setId(tAbbMember1.getId());
			memberMapper.updateByPrimaryKeySelective(tAbbMember);
		}
        //提现成功给后台返还佣金
		if (record.getStatus()==2){
			if (tAbbWithdraw.getSfee()>0){
				TAbbMember shangjitAbbMember=new TAbbMember();//购买商品的上级用户实体
				//判断是否有上级用户
				if (tAbbMember1.getYqrid()!=null){
					shangjitAbbMember=tAbbMemberMapper.selectByPrimaryKey(tAbbMember1.getYqrid());
					//增加上级用户账户的钱
					TAbbMember tAbbMember3=new TAbbMember();
					tAbbMember3.setId(shangjitAbbMember.getId());
					tAbbMember3.setAccount(shangjitAbbMember.getAccount()+tAbbWithdraw.getSfee());
					tAbbMemberMapper.updateByPrimaryKeySelective(tAbbMember3);

					TAbbCommission tAbbCommission3=new TAbbCommission();
					tAbbCommission3.setCreattime(DateUtil.getCurrentDateTimeStr());
					tAbbCommission3.setType(1);
					tAbbCommission3.setBeiyongone(String.valueOf(tAbbWithdraw.getSfee()));
					tAbbCommission3.setBusinessid("1");
					tAbbCommission3.setMemberid(tAbbMember3.getId());
					tAbbCommission3.setMessage("下级提现抽成!");
					tAbbCommission3.setId(SnowflakeIdWorker.getUUID());
					tAbbCommissionMapper.insertSelective(tAbbCommission3);
				}

			}
			if (tAbbWithdraw.getFee()>0){
				//增加平台账户的钱
				TAbbCountExample example1=new TAbbCountExample();
				List<TAbbCount> listcount=tAbbCountMapper.selectByExample(example1);
				TAbbCount tAbbCount=listcount.get(0);
				tAbbCount.setCount(tAbbCount.getCount()+tAbbWithdraw.getFee());
				tAbbCountMapper.updateByPrimaryKeySelective(tAbbCount);


				//添加后台佣金记录
				TAbbCommission tAbbCommission2=new TAbbCommission();
				tAbbCommission2.setCreattime(DateUtil.getCurrentDateTimeStr());
				tAbbCommission2.setType(3);
				tAbbCommission2.setBeiyongone(String.valueOf(tAbbWithdraw.getFee()));
				tAbbCommission2.setBusinessid("1");
				tAbbCommission2.setMemberid(tAbbMember1.getId());
				tAbbCommission2.setMessage(tAbbMember1.getNicename()+"提现了:"+tAbbWithdraw.getTotalmoney()+"系统获得了"+tAbbWithdraw.getFee()+"元手续费!");//tAbbMember1.getNicename()+"提现了:"+tAbbWithdraw.getTotalmoney()+"系统获得了"+tAbbWithdraw.getFee()+"元手续费!"
				tAbbCommission2.setId(SnowflakeIdWorker.getUUID());
				tAbbCommissionMapper.insertSelective(tAbbCommission2);
			}

		}


		return tAbbWithdrawMapper.updateByPrimaryKeySelective(record);
    }
}
